package com.work.game.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateManager {
    private Context mContext; //上下文

    private String apkUrl ; //apk下载地址
    private static final String savePath = "/sdcard/updateAPK/"; //apk保存到SD卡的路径
    private static final String saveFileName = savePath + "kyj.apk"; //完整路径名

    private ProgressBar mProgress; //下载进度条控件
    private static final int DOWNLOADING = 1; //表示正在下载
    private static final int DOWNLOADED = 2; //下载完毕
    private static final int DOWNLOAD_FAILED = 3; //下载失败
    private int progress; //下载进度
    private boolean cancelFlag = false; //取消下载标志位

    //    private double serverVersion = 2.0; //从服务器获取的版本号
//    private double clientVersion = 1.0; //客户端当前的版本号
//    private String updateDescription = "更新地址：http://www-m2.com/android/m2.apk"; //更新内容描述信息
//    private boolean forceUpdate = true; //是否

    private AlertDialog alertDialog2; //表示提示对话框、进度条对话框

    /**
     * 构造函数
     */
    public UpdateManager(Context context) {
        this.mContext = context;
    }


    /**
     * 显示进度条对话框
     */
    public void showDownloadDialog(ProgressBar mProgress, AlertDialog alertDialog2, String url) {
        this.apkUrl = url;
        this.mProgress = mProgress;
        this.alertDialog2 = alertDialog2;
        //下载apk
        downloadAPK();
    }

    /**
     * 下载apk的线程
     */
    public void downloadAPK() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(apkUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();

                    InputStream is = conn.getInputStream();
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }

                    String apkFile = saveFileName;
                    File ApkFile = new File(apkFile);
                    if (!ApkFile.exists()) {
                        ApkFile.createNewFile();//创建文件
                    }

                    // File file2 = Environment.getDataDirectory();

                    // File file1 =new File(file2,"m2.apk");
                    //   createFile();

                    FileOutputStream fos = new FileOutputStream(apkFile);
                    updateFile = ApkFile;
                    // FileOutputStream fos =mContext.openFileOutput( updateFile.getPath(), Activity.MODE_PRIVATE);
                    int count = 0;
                    byte buf[] = new byte[1024];

                    do {

                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        //更新进度
                        mHandler.sendEmptyMessage(DOWNLOADING);
                        if (numread <= 0) {
                            //下载完成通知安装
                            fos.flush();
                            fos.close();
                            is.close();
                            mHandler.sendEmptyMessage(DOWNLOADED);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!cancelFlag); //点击取消就停止下载.

                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 创建file文件
     *
     * @param sd_available    sdcard是否可用
     */
    File updateDir;
    File updateFile;


    /**
     * 更新UI的handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOADED:
                    if (alertDialog2 != null)
                        alertDialog2.dismiss();
                    installAPK();
                    break;
                case DOWNLOAD_FAILED:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        Toast.makeText(mContext, "请允许访问管理文件", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(mContext, "网络断开，请稍候再试", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 下载完成后自动安装apk
     */
    public void installAPK() {
//        File apkFile = new File(saveFileName);
//        if (!apkFile.exists()) {
//            return;
//        }
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(Uri.parse("file://" + updateFile.toString()), "application/vnd.android.package-archive");
//        mContext.startActivity(intent);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", updateFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(updateFile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }
}
